const http = require('http');
// console.log(http);

// 创建本地服务器来从其接收数据
var server = http.createServer(async function (req, res) { // 接收到请求时执行的回调函数
    // req  => request 
    // res  => response
    // console.log(111111);

    if (req.url != "/favicon.ico") {  //排除网页标题图标
        console.log("接收到请求!!!");

        var url = req.url;
        console.log(url);
        if (url == "/") {

            var baseUrl = __dirname;
            const fs = require('fs/promises');
            const path = require('path');
            const { readFile } = fs;

            var result = await readFile(path.join(baseUrl, "../site/index.html"), "utf-8")
            // console.log(result);

            res.write(result);

        } else if (url == "/html/login.html") {
            var baseUrl = __dirname;
            const fs = require('fs/promises');
            const path = require('path');
            const { readFile } = fs;

            var result = await readFile(path.join(baseUrl, "../site", "/html/login.html"))
            // console.log(result);

            res.write(result);
        } else if (url == "/images/2.jpg") {
            var baseUrl = __dirname;
            const fs = require('fs/promises');
            const path = require('path');
            const { readFile } = fs;

            var result = await readFile(path.join(baseUrl, "../site", "/images/2.jpg"))
            console.log(result);

            res.write(result);
        } else if (url == "/css/index.css") {
            var baseUrl = __dirname;
            const fs = require('fs/promises');
            const path = require('path');
            const { readFile } = fs;
            var result = await readFile(path.join(baseUrl, "../site", url))

            res.write(result);
        } else if (url == "/js/index.js") {
            var baseUrl = __dirname;
            const fs = require('fs/promises');
            const path = require('path');
            const { readFile } = fs;
            var result = await readFile(path.join(baseUrl, "../site", url))

            res.write(result);
        }

    }

    res.end();

})
// console.log(server);

server.listen(3000, function () { // 服务启动时执行的回调函数
    console.log("服务已启动:localhost:3000");
})